<?php
declare (strict_types=1);

namespace app\exam\service\admin;

use app\common\service\BaseService;
use eduline\admin\libs\pageform\FormItem;
use eduline\admin\page\PageForm;
use think\annotation\Inject;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\facade\Request;
use think\Response;

/**
 * Class ModuleConfig
 *
 * @package app\exam\service\admin
 */
class ModuleConfig
{
    /**
     * @Inject()
     *
     * @var \app\exam\logic\admin\Module
     */
    protected $moduleLogic;
    /**
     * @Inject()
     *
     * @var \app\exam\logic\admin\ModuleConfig
     */
    protected $moduleConfigLogic;

    /**
     * @Inject()
     *
     * @var \app\exam\logic\admin\QuestionPoint
     */
    protected $questionPointLogic;

    /**
     * 知识点配置
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2021/1/28
     *
     * @param int $moduleId
     * @return \eduline\admin\page\interfaces\think\Response|Response
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function pointConfig(int $moduleId)
    {
        if (Request::post()) {
            $data = Request::post();
            $this->moduleConfigLogic->saveModuleConfig($moduleId, $data);

            return BaseService::parseToData([], 1, '保存成功');
        }
        $module       = $this->moduleLogic->findOrFail($moduleId);
        $data         = $this->moduleConfigLogic->getModuleConfigByModuleId($moduleId);
        $pointOptions = $this->questionPointLogic->cascader();
        // 创建课程界面配置
        $keyList = [
            'module_title'   => FormItem::make()->title('版块名称')->disabled(),
            'limit'          => FormItem::make('inputNumber')->title('知识点个数')->min(1)->max(20)->required()->help('1. 单次练习时可同时选择的知识点数量<br />2. 最多支持20个'),
            'question_count' => FormItem::make('inputNumber')->title('出题数量')->min(1)->max(500)->required()->help('1. 单次练习时，针对出题限制最大数量<br />2. 最大支持500道题'),
            'point'          => FormItem::make('cascader')->title('知识点')->options($pointOptions)->multiple(true)->required()
        ];
        // 设置表单
        $form = new PageForm();
        // 表单字段
        if ($data->isEmpty()) {
            $datas = [
                'module_title' => $module->getAttr('title'),
            ];
        } else {
            $config = $data->getAttr('value');
            $datas  = [
                'module_title'   => $module->getAttr('title'),
                'limit'          => $config['limit'],
                'question_count' => $config['question_count'],
                'point'          => $config['point']
            ];
        }

        $form->datas       = $datas;
        $form->pageKey     = $keyList;
        $form->saveMethod  = 'POST';
        $form->savePostUrl = '/exam/admin/module/' . $moduleId . '/point/config';

        return $form->send();
    }

}